﻿using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using Edu.Http;
using Edu.Http.Extensions;
using Edu.Http.Proxy;
using Infrastructure.Config.Core.External;
using Infrastructure.ExternalService.Core.Imp.Extensions;
using Infrastructure.ExternalService.Core.Marketing;
using Infrastructure.ExternalService.Core.Requests;
using Infrastructure.ExternalService.Core.Responses;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Volo.Abp;

namespace Infrastructure.ExternalService.Core.Imp.Marketing
{
    public class MarketingExternal : BaseHttpClient, IMarketingExternal
    {
        private readonly OrderCenterApiOptions _orderingOptions;
        public IAccessTokenProvider TokenProvider { get; set; }

        public MarketingExternal(IOptions<OrderCenterApiOptions> options,
            HttpClient client, ILoggerFactory loggerFactory)
            : base(client, loggerFactory, options.Value.MarketingOptions.EndPoint)
        {
            _orderingOptions = options.Value ?? throw new HttpProxyException($"{nameof(MarketingExternal)}配置获取失败");
            loggerFactory.CreateLogger<MarketingExternal>();
        }

        /// <summary>
        /// 设置BaseHttpClient的BaseAddress：该值默认是从构造函数传入的，但重写该方法可以改变该值
        /// </summary>
        /// <returns></returns>
        protected override string SetHttpClientBaseAddress()
        {
            return null;
        }

        #region 接口实现方法
        public async Task<RegisterCustomerResponse> RegisterCustomer(string custId)
        {
            var response = await PutAsync<WrapResponse<RegisterCustomerResponse>>($"{_orderingOptions.MarketingOptions.CustomerRegister}/{custId}");
            if (response.Code.Equals(ClientReturnCode.Success))
            {
                return response.Data;
            }
            throw new HttpProxyException($"{response.Msg}");
        }
        public async Task<string> AddOrUpdateCustomerProjectInfoAsync(AddOrUpdateCustomerProjectRequest request)
        {
            var response = await PostAsync<WrapResponse<string>>(_orderingOptions.MarketingOptions.AddOrUpdateCustomerProjectInfo, request);
            if (response.Code.Equals(ClientReturnCode.Success))
            {
                return response.Data;
            }
            throw new HttpProxyException($"{response.Msg}");
        }

        public async Task<List<CustomerProfile>> GetCustomersAsync(GetCustomersRequest request)
        {
            var response = await PostAsync<WrapResponse<List<CustomerProfile>>>(_orderingOptions.MarketingOptions.GetCustomersByUserIds, request);
            if (response.Code.Equals(ClientReturnCode.Success))
            {
                return response.Data;
            }
            throw new HttpProxyException($"{response.Msg}");
        }

        public async Task<string> SetCustomersLabelAsync(SetCustomersLabelRequest request)
        {

            base.SetHeader("authorization", request.authorization);
            base.SetHeader("checkCode", request.Header);
            var response = await PostAsync<WrapResponse<string>>(_orderingOptions.MarketingOptions.SetCustomerLabel, request);
            if (response.Code.Equals(ClientReturnCode.Success))
            {
                return response.Data;
            }
            throw new HttpProxyException($"{response?.Msg}");
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<CustomerProfile> GetCustomerByCustIdAsync(string custId)
        {
            try
            {
                var response = await GetAsync($"{_orderingOptions.MarketingOptions.GetCustomerByCustId}/{custId}");
                return await response.ConvertToWrapResponse<CustomerProfile>();
            }
            catch (System.Exception ex)
            {
                throw new UserFriendlyException(ex.Message);
            }
        }
        /// <summary>
        /// 通过手机号, 品牌标识获取客户信息
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<CustomerProfile> GetCustomerByMobileAsync(GetCustomerProfileByMobileRequest request)
        {
            try
            {
                var response = await GetAsync(_orderingOptions.MarketingOptions.GetCustomerByMobile, request);
                return await response.ConvertToWrapResponse<CustomerProfile>();
            }
            catch (System.Exception ex)
            {
                throw new UserFriendlyException(ex.Message);
            }
        }

        /// <summary>
        /// 通过客户UserId,获取客户信息
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<CustomerProfile> GetCustomerByUserIdAsync(GetCustomerProfileByUserIdRequest request)
        {
            try
            {
                var response = await GetAsync(_orderingOptions.MarketingOptions.GetCustomerByUserId, request);
                return await response.ConvertToWrapResponse<CustomerProfile>();
            }
            catch (System.Exception ex)
            {
                throw new UserFriendlyException(ex.Message);
            }
        }


        /// <summary>
        /// 创建线索
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<ClueResponse> CreateClueAsync(CreateClueRequest request)
        {
            var response = await PostAsync<WrapResponse<ClueResponse>>(_orderingOptions.MarketingOptions.ClueCreate, request);
            if (response.Code.Equals(ClientReturnCode.Success))
            {
                if (response.Data == null)
                {
                    throw new HttpProxyException("线索创建失败");
                }
                return response.Data;
            }
            throw new HttpProxyException($"{response.Msg}");
        }

        public async Task<List<CustomerProject>> GetCustomerProjectInfo(GetCustomerProjectInfoRequest request)
        {
            try
            {
                var response = await GetAsync(_orderingOptions.MarketingOptions.GetCustomerProjectInfo, request);
                return await response.ConvertToWrapResponse<List<CustomerProject>>();
            }
            catch (System.Exception ex)
            {
                throw new UserFriendlyException(ex.Message);
            }
        }
        #endregion
    }
}
